﻿package 
{
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	public class LoaderVDD extends EventDispatcher
	{
		private static var m_instance:LoaderVDD = null;
		public var mVDDMap:Dictionary = new Dictionary;
		
		public var mPreLoader:LoaderVDD = null;
		private var mResPath:String = "";
		private var mLoad:int = 0;
		private var mLoaded:int = 0;
		
		private const TIME_DELAY:int = 1000;
		private var mLoadFrame:int = 0;
		private var mUpdateTick:int = 0;
		private var mFreeTime:Timer = new Timer(TIME_DELAY);
		
		private var mBuffers:Array = [];
		private var _testTime:int;
		private var _testCount:int = 2;
		private var _errorCheckTime:Number = 0;//错误检测
		
		public static function instance():LoaderVDD
		{
			if(m_instance == null)
			{
				m_instance = new LoaderVDD;
			}
			return m_instance;
		}
		
		public function LoaderVDD()
		{
			mFreeTime.addEventListener(TimerEvent.TIMER, handleFreeTimeTimer);
			mFreeTime.start();
			
			this.addEventListener(Event.COMPLETE, onComplete);
		}
		public function TheInit(preload:LoaderVDD):void
		{
		        mPreLoader = preload;
		}
		public function TheDest():void
		{
			mResPath = "";
			for each( var vdd:VDD in mVDDMap )
			{
				vdd.TheDest();
			}
			mVDDMap = new Dictionary();
//			mPreLoader = null;
//			mFreeTime.stop();
//			mFreeTime.removeEventListener(TimerEvent.TIMER, handleFreeTimeTimer);
		}
		/**
		 * 启动开始队列加载
		 */
		public function startLoad():void
		{
			onComplete(null);
		}
		private function onComplete(e:Event):void
		{
			var count:int = 0;
			for(var key:* in mVDDMap){
				count ++;
			}
			
			//超过10个则暂时不处理，等图片输出完了再加载
			if(count < 10){
				if(mBuffers.length){
					this.LoadVDD(mBuffers.shift(), true);
				}
				if(mBuffers.length){
					this.LoadVDD(mBuffers.shift(), true);
				}
			}
		}
		private function handleFreeTimeTimer(e:TimerEvent):void
		{
			var nowtime:Number = new Date().time;
			if(nowtime - _errorCheckTime > 1000 * 30){//大于30秒了还没反应，强制加载执行下一个。
				onComplete(null);
			}
			
//			var loc4:int;
//			if(_testTime == 0)
//			{
//				_testTime = new Date().time;
//			}
//			else
//			{
//				loc4 = new Date().time;
//				trace("打包FPS[" + (loc4 - _testTime) + "]");
//				if(loc4 - _testTime < TIME_DELAY * 1.8)
//				{
//					_testCount ++;
//					if(_testCount > 10){
//						_testCount = 10;
//					}
//				}
//				else
//				{
//					_testCount -= 10;
//					if(_testCount < 0)
//					{
//						_testCount = 0;
//					}
//				}
//				_testTime = loc4;
//			}
//			var loc2:Array = [];
//			var loc3:int = 0;
//			while(loc3++ < _testCount)
//			{
//				if(mBuffers.length)
//				{
//					loc2.push(mBuffers.shift());
//				}
//			}
//			loc3 = 0;
//			while(loc3 < loc2.length)
//			{
//				this.LoadVDD(loc2[loc3], true);
//				loc3 ++;
//			}
		}
		private function handleComplate(e:Event):void 
		{
			var loader:VDDLoader = e.target as VDDLoader;
			
			_errorCheckTime = new Date().time;
			if(e.type == 'complete') 
			{
				try
				{
					if(VDD.resType == 0)
					{
						loader.vdd.TheInit(loader.data);	
					}
					else
					{
						loader.vdd.TheJson(loader.data);	
					}
				}
				catch (e:Error)
				{
					onComplete(null);
					trace("出错2---------------------LoaderVDD.handleComplate-----------------------" + loader.vdd.url);
				}
			}
			else
			{
				trace(loader.vdd.url);
				throw new Error("出错---------------------LoaderVDD.handleComplate-----------------------" + loader.vdd.url);
			}
			loader.removeEventListener(Event.COMPLETE, handleComplate);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, handleComplate);
			loader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, handleHttpStatus);
			loader.vdd = null;
			loader.close();
			mLoaded ++;
			
		}
		private function handleHttpStatus(e:HTTPStatusEvent):void 
		{
			if ( e.status != 200 )
			{
				mLoaded ++;
				onComplete(null);
			}
		}

		public function LoadVDD(url:String,add_pre:Boolean=false, nativePath:String=null):VDD
		{
			var vdd:VDD;
//			url = url.toLocaleLowerCase();
			if(!add_pre)
			{
				this.mBuffers.push(url);
				return null;
			}
			
			_errorCheckTime = new Date().time;
			
			if (!mVDDMap[url])
			{
				if( mPreLoader && mPreLoader.mVDDMap[url] )
				{
					vdd = mPreLoader.mVDDMap[url] as VDD;
					return vdd;
				}
				else
				{
					vdd = new VDD();
				
					if ( add_pre && mPreLoader )
					{
						mPreLoader.mVDDMap[url] = vdd;
					}
					else
					{
						mVDDMap[url] = vdd;
					}
					
					mLoad ++;
					var loader:VDDLoader = new VDDLoader;
					vdd.url = url;
					loader.vdd = vdd;
					if(VDD.resType == 0)
					{
						loader.dataFormat = URLLoaderDataFormat.BINARY;
					}
					else
					{
						loader.dataFormat = URLLoaderDataFormat.TEXT;
					}
					loader.addEventListener(Event.COMPLETE, handleComplate);
					loader.addEventListener(IOErrorEvent.IO_ERROR, handleComplate);
					loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, handleHttpStatus);
					loader.load(new URLRequest(url));
                    //trace(mResPath + 'data/' + url + '.vdd');
					return vdd;
				}
			}
			else
			{
				vdd = mVDDMap[url] as VDD;
				return vdd;
			}
			return null;
		}
		
	}

	
}


import flash.net.URLLoader;

class VDDLoader extends URLLoader
{
	public var vdd:VDD;
	
	public function VDDLoader()
	{
		super();
	}
}